//
//  FYUserAccount.swift
//  Weibo
//
//  Created by 冯毅 on 16/8/9.
//  Copyright © 2016年 冯毅. All rights reserved.
//

import UIKit

class FYUserAccount: NSObject, NSCoding {
    
    var access_token: String?
    
    var expiresDate: NSDate?
    
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
    
    var uid: Int64 = 0
    
    var name: String?
    
    var avatar_large: String?
    
    init(dic: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dic)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description: String {
        let keys = ["access_token", "expires_in", "name", "avatar_large"]
        
        return dictionaryWithValuesForKeys(keys).description
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeInt64ForKey("uid")
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
    }
    
    func saveUserAccount() {
//        let path = (NSSearchPathForDirectoriesInDomains(.DocumentationDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("userAccount.archive")
        let path = (NSHomeDirectory() as NSString).stringByAppendingPathComponent("userAccount.archive")
//        print(path)
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    class func loadUserAccount() -> FYUserAccount?{
//        let path = (NSSearchPathForDirectoriesInDomains(.DocumentationDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("userAccount.archive")
        let path = (NSHomeDirectory() as NSString).stringByAppendingPathComponent("userAccount.archive")
        print(path)


        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? FYUserAccount
        
    }
}
